package com.corecmd.tcloud.tcgateway.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.Charsets;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author : TianShaoJiao
 * @date : 2021/1/29
 * @description :
 **/
public class HttpUtil {
    private static Logger log = LoggerFactory.getLogger(HttpUtil.class);
    public static String httpFormPost(String url, Map<String,String> params, Map<String,String> headers, Charset charset) throws Exception{
        log.info("发起HTTP POST请求：" + url);
        String requestResult = null;
        CloseableHttpClient closeableHttpClient = HttpUtil.createSSLClientDefault();
        HttpPost httpPost = new HttpPost(url);
        if (null == charset){
            charset = Charsets.toCharset("UTF-8");
        }
        if (null != headers && !headers.isEmpty()){
            for (Map.Entry<String,String> entry:headers.entrySet()) {
                httpPost.addHeader(entry.getKey(),entry.getValue());
            }
        }
        if (null != params && !params.isEmpty()){
            List<NameValuePair> list = new ArrayList< NameValuePair>();
            for (Map.Entry<String,String> entry:params.entrySet()) {
                NameValuePair pai1 = new BasicNameValuePair(entry.getKey(),entry.getValue());
            }
            HttpEntity httpEntity = new UrlEncodedFormEntity(list);
            httpPost.setEntity(httpEntity);
        }
        CloseableHttpResponse closeableHttpResponse = closeableHttpClient.execute(httpPost);
        if (null != closeableHttpResponse){
            HttpEntity httpEntity = closeableHttpResponse.getEntity();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpEntity.getContent(), charset));
            String tempStr = "";
            StringBuffer sb = new StringBuffer();
            while ( (tempStr = bufferedReader.readLine()) != null){
                sb.append(tempStr);
            }
            bufferedReader.close();
            requestResult = sb.toString();
        }
        if (null != closeableHttpResponse){
            closeableHttpResponse.close();
        }
        closeableHttpClient.close();
        log.info("请求结果："+requestResult);
        return requestResult;
    }
    public static String httpPost(String url,Map<String,String> params, Map<String,String> headers, Charset charset) throws Exception{
        log.info("发起HTTP POST请求：" + url);
        String requestResult = null;
        CloseableHttpClient closeableHttpClient = HttpUtil.createSSLClientDefault();
        HttpPost httpPost = new HttpPost(url);
        if (null == charset){
            charset = Charsets.toCharset("UTF-8");
        }
        if (null != headers && !headers.isEmpty()){
            for (Map.Entry<String,String> entry:headers.entrySet()) {
                httpPost.addHeader(entry.getKey(),entry.getValue());
            }
        }
        if (null != params && !params.isEmpty()){
            JSONObject jsonObject = (JSONObject) JSON.toJSON(params);
            String requestParams = jsonObject.toJSONString();
            HttpEntity httpEntity = new StringEntity(requestParams, charset);
            httpPost.setEntity(httpEntity);
        }
        CloseableHttpResponse closeableHttpResponse = closeableHttpClient.execute(httpPost);
        if (null != closeableHttpResponse){
            HttpEntity httpEntity = closeableHttpResponse.getEntity();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpEntity.getContent(), charset));
            String tempStr = "";
            StringBuffer sb = new StringBuffer();
            while ( (tempStr = bufferedReader.readLine()) != null){
                sb.append(tempStr);
            }
            bufferedReader.close();
            requestResult = sb.toString();
        }
        if (null != closeableHttpResponse){
            closeableHttpResponse.close();
        }
        closeableHttpClient.close();
        log.info("请求结果："+requestResult);
        return requestResult;
    }
    public static String httpGet(String url, Map<String,String> headers, Charset charset) throws Exception{
        log.info("发起HTTP Get请求：" + url);
        String requestResult = null;
        CloseableHttpClient closeableHttpClient = HttpUtil.createSSLClientDefault();
        HttpGet httpGet = new HttpGet(url);
        if (null == charset){
            charset = Charsets.toCharset("UTF-8");
        }
        if (null != headers && !headers.isEmpty()){
            for (Map.Entry<String,String> entry:headers.entrySet()) {
                httpGet.addHeader(entry.getKey(),entry.getValue());
            }
        }
        CloseableHttpResponse closeableHttpResponse = closeableHttpClient.execute(httpGet);
        if (null != closeableHttpResponse){
            HttpEntity httpEntity = closeableHttpResponse.getEntity();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpEntity.getContent(), charset));
            String tempStr = "";
            StringBuffer sb = new StringBuffer();
            while ( (tempStr = bufferedReader.readLine()) != null){
                sb.append(tempStr);
            }
            bufferedReader.close();
            requestResult = sb.toString();
        }
        if (null != closeableHttpResponse){
            closeableHttpResponse.close();
        }
        closeableHttpClient.close();
        return requestResult;
    }
    public static CloseableHttpClient createSSLClientDefault(){
        CloseableHttpClient closeableHttpClient = null;
        try {
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                    return true;
                }
            }).build();
            HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
            SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext,hostnameVerifier);
            closeableHttpClient = HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build();
        } catch (Exception e) {
            log.info("解决Https异常",e);
        }
        return closeableHttpClient;
    }
}
